package com.ec.core.annotation;

/**
 * <p>Title: ec</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2008 7</p>
 *
 * <p>Company: ec</p>
 *
 * @author pgf
 * @version 1.0
 */
import java.util.Hashtable;
import com.ec.core.dao.*;
import java.lang.annotation.*;
import java.lang.reflect.Method;

public class AnnotationUtil {
    private static Hashtable<String,DataTableMeta> classMeta = new Hashtable<String,DataTableMeta>(); // className/classAnnotation
    public AnnotationUtil() {

    }
    public static DataTableMeta getDataTableMeta(Class currentClass){
        if(classMeta.containsKey(currentClass.getName())){
            return (DataTableMeta)classMeta.get(currentClass.getName());
        }else{
            Hashtable<String,DataFieldMeta> fields  = new Hashtable<String,DataFieldMeta>();
            String pkName = null;
        	 Method[] methods = currentClass.getDeclaredMethods();
             for(Method method:methods){
                 Annotation[] methodAnno = method.getDeclaredAnnotations();
                 for(Annotation mAnno:methodAnno){
                     if(mAnno instanceof Field && method.getName().startsWith("get")){
                         Field field = (Field)mAnno;
                         DataFieldMeta dfm = new DataFieldMeta();
                         dfm.setFieldName(field.name().toUpperCase());
                         dfm.setPk(field.pk());
                         dfm.setReadonly(field.readonly());
                         String methodName = method.getName().substring(3);
                         dfm.setMethodName(methodName);
                         dfm.setReturnType(method.getReturnType().getName());
                         if(field.pk()){
                        	 pkName = field.name().toUpperCase();
                         }
                         
                         fields.put(methodName, dfm);
                     }
                 }
             }
            DataTableMeta dtm = new DataTableMeta();
            dtm.setFields(fields);
            dtm.setPkName(pkName);
            Annotation[] anno = currentClass.getDeclaredAnnotations();
            for (int i = 0; i < anno.length; i++) {
                if (anno[i] instanceof Table) {
                    Table table = (Table) anno[i];
                    dtm.setTableName(table.name());	
                    break;
                }
            }
            classMeta.put(currentClass.getName(),dtm);
            return dtm;
        }
    }
}
